package guda.mrpc.core.codec;

import guda.mrpc.core.serialize.ObjectSerialize;
import io.netty.buffer.ByteBuf;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.channel.ChannelHandlerContext;


import java.util.List;

/**
 * Created by well on 17/5/23.
 */
public class ObjectDecoder extends ByteToMessageDecoder {

    private ObjectSerialize objectSerialize;
    private Class<?> genericClass;

    public ObjectDecoder(ObjectSerialize objectSerialize, Class<?> genericClass) {
        this.objectSerialize = objectSerialize;
        this.genericClass = genericClass;
    }


    @Override
    public final void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        if (in.readableBytes() < 4) {
            return;
        }
        in.markReaderIndex();
        int dataLength = in.readInt();
        if (in.readableBytes() < dataLength) {
            in.resetReaderIndex();
            return;
        }
        byte[] data = new byte[dataLength];
        in.readBytes(data);
        Object obj = objectSerialize.deserialize(data, genericClass);
        out.add(obj);
    }
}
